/*
 * Copyright (c) 2022  by Junzhao
 * THIS FILE IS PART OF JAVASE Song Huongkang PROJECT
 * All Rights Reserved.
 */

package 线程安全.Lock锁方式;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @description JDK5.0之后新增 需要手动控制 也更加灵活
 *
 * @author 俊昭
 * @date 2022/4/13
*/
public class LockTest {
    public static void main(String[] args) {
        Window w1 =new Window();
        Thread t1 = new Thread(w1,"窗口一");
        Thread t2 = new Thread(w1,"窗口二");
        Thread t3 = new Thread(w1,"窗口三");

        t1.start();
        t2.start();
        t3.start();

    }
}
class Window implements Runnable{
    private int ticket = 1000;
    private ReentrantLock lock = new ReentrantLock(true);// 公平的分配“先来后到”


    @Override
    public void run() {
        while(true){
            try{
                // 调用lock()锁定
                lock.lock();
                if (ticket>0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"售票 x1 号码为："+ticket);
                    ticket--;
                }else{
                    break;
                }
            }finally {
                // 调用unlock()解锁
                lock.unlock();
            }

        }
    }
}